<?php

declare(strict_types=1);

namespace SixShop\Wangdian\Services;

use SixShop\Wangdian\Client;
use SixShop\Wangdian\Response\ApiResponse;

/**
 * Base service class for all API services
 */
abstract class BaseService
{
    public function __construct(
        protected readonly Client $client
    ) {
    }

    /**
     * Make an API call through the client
     */
    protected function call(string $endpoint, array $params = []): ApiResponse
    {
        return $this->client->call($endpoint, $params);
    }

    /**
     * Validate required parameters
     */
    protected function validateRequired(array $params, array $required): void
    {
        foreach ($required as $field) {
            if (!isset($params[$field]) || 
                (is_string($params[$field]) && empty(trim($params[$field]))) ||
                (is_array($params[$field]) && empty($params[$field]))
            ) {
                throw new \InvalidArgumentException("Required parameter '{$field}' is missing or empty");
            }
        }
    }

    /**
     * Filter out null and empty values from parameters
     */
    protected function filterParams(array $params): array
    {
        return array_filter($params, function ($value) {
            return $value !== null && $value !== '';
        });
    }

    /**
     * Convert array to JSON string if needed
     */
    protected function encodeIfArray(mixed $value): mixed
    {
        return is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
    }
}